//
//  MemoryTradingViewController.m
//  Bees
//
//  Created by NowYouCanSee on 2019/1/23.
//  Copyright © 2019 xiaohan. All rights reserved.
//

#import "MemoryTradingViewController.h"
#import "XHomeSegementView.h"
#import "UIColor+GradualChanging.h"
#import "EOSService.h"
@interface MemoryTradingViewController ()<UITextFieldDelegate>
@property (nonatomic,strong) UILabel*memoryLab;
@property (nonatomic,strong) UILabel*memoryUnitPriceLab;
@property (nonatomic,strong) UILabel*valueLab;
@property (nonatomic,weak) UILabel*useTip;
@property (nonatomic,strong) UITextField*numTF;
@property (nonatomic,strong) UITextField*accountTF;
@property (nonatomic,strong) EOSService *eosService;
@property (nonatomic,assign) BOOL isSell;

@end

@implementation MemoryTradingViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
    [self getaccountInfo];
}

- (void)getaccountInfo{
    [self.eosService getAccountInfoComplete:^(BOOL success, NSString * _Nonnull errorMsg) {
        if (success) {
            NSString*ram_quota = self.eosService.accountResult.ram_quota;
            NSString*ram_usage = self.eosService.accountResult.ram_usage;
            if (!IsNilOrNull(ram_quota) && !IsNilOrNull(ram_usage)) {
                NSString*available = handlerDecimalNumber(SNDiv(SNSub(ram_quota, ram_usage), @1024), NSRoundDown, 2).stringValue;
                self.memoryLab.text = [NSString stringWithFormat:@"%@ KB",available];
                self.eosService.accountResult.ram_remaining = available;
            }else{
                self.memoryLab.text = [NSString stringWithFormat:@"%@ KB",@"0.00"];
            }
            if (self.isSell) {
                self.useTip.text = [NSString stringWithFormat:@"%@：%@ KB",XLocalized(@"余额"),self.eosService.accountResult.ram_remaining];
            }else{
                self.useTip.text = [NSString stringWithFormat:@"%@：%@",XLocalized(@"余额"),self.eosService.accountResult.core_liquid_balance];
            }
        }else{
            [self.view makeToast:errorMsg];
        }
    }];
    [self.eosService getRammarketComplete:^(BOOL success, NSString * _Nonnull errorMsg) {
        if (success) {
            self.memoryUnitPriceLab.text = self.eosService.ram_balance;
        }else{
            [self.view makeToast:errorMsg];
        }
    }];
}

- (void)setupUI{
    self.title = XLocalized(@"RAM交易");
    UIView*headView = [[UIView alloc]initWithFrame:CGRectMake(kNormalSpace, kNormalSpace, kScreenWidth-2*kNormalSpace, AdaptedWidth(100))];
    [headView.layer insertSublayer:[UIColor setGradualChangingFrame:CGRectMake(0, 0, headView.width, headView.height) fromColor:[kGradientColors firstObject] toColor:[kGradientColors lastObject]] atIndex:0];
    ViewRadius(headView, AdaptedWidth(10));
    [self.contentView addSubview:headView];
    XHomeSegementView*segementView = [[XHomeSegementView alloc]initWithFrame:CGRectMake((kScreenWidth-AdaptedWidth(120))*.5,headView.bottom+AdaptedWidth(30),AdaptedWidth(120), KHomeSegementHeight)];
    segementView.fixedWidth = AdaptedWidth(60);
    segementView.titles =@[XLocalized(@"买入"),XLocalized(@"出售")];
    [self.contentView addSubview:segementView];
    
    self.memoryLab = [UILabel new];
    self.memoryLab.textColor = [UIColor whiteColor];
    self.memoryLab.font = kBoldFont(25);
    self.memoryLab.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:self.memoryLab];
    [self.memoryLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(AdaptedWidth(25));
        make.left.mas_equalTo(0);
    }];
    self.memoryUnitPriceLab = [UILabel new];
    self.memoryUnitPriceLab.textColor = [UIColor whiteColor];
    self.memoryUnitPriceLab.font = kBoldFont(25);
    self.memoryUnitPriceLab.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:self.memoryUnitPriceLab];
    [self.memoryUnitPriceLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.memoryLab.mas_top);
        make.left.equalTo(self.memoryLab.mas_right);
        make.right.mas_equalTo(0);
        make.width.equalTo(self.memoryLab.mas_width);
    }];
   
    UILabel*ramtip = [UILabel new];
    ramtip.textColor = UIColor.whiteColor;
    ramtip.font = kDefaultFont(13);
    ramtip.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:ramtip];
    [ramtip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.memoryLab.mas_centerX);
        make.bottom.mas_equalTo(-AdaptedWidth(25));
    }];
    ramtip.text = XLocalized(@"可用RAM");

    UILabel*unittip = [UILabel new];
    unittip.textColor = UIColor.whiteColor;
    unittip.font = kDefaultFont(13);
    unittip.textAlignment = NSTextAlignmentCenter;
    [headView addSubview:unittip];
    [unittip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.memoryUnitPriceLab.mas_centerX);
        make.bottom.mas_equalTo(-AdaptedWidth(25));
    }];
    unittip.text = XLocalized(@"当前价格(EOS/KB)");
    
    UILabel*actionTip = [UILabel new];
    actionTip.textColor = UIColorHex(333333);
    actionTip.font = kDefaultFont(15);
    [self.contentView addSubview:actionTip];
    [actionTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kNormalSpace);
        make.top.equalTo(segementView.mas_bottom).offset(AdaptedWidth(20));
    }];
    
    UILabel*useTip = [UILabel new];
    useTip.textColor = UIColorHex(666666);
    useTip.font = kDefaultFont(13);
    [self.contentView addSubview:useTip];
    [useTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(-kNormalSpace);
        make.centerY.equalTo(actionTip.mas_centerY);
    }];
    self.useTip = useTip;
    
    self.numTF = [UITextField new];
    [self.numTF setValue:@20 forKey:Limit_NAME];
    self.numTF.delegate = self;
    [self.contentView addSubview:self.numTF];
    [self.numTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.top.equalTo(actionTip.mas_bottom).offset(5);
        make.height.mas_equalTo(AdaptedWidth(37));
    }];
    UIView*letfV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, AdaptedWidth(30))];
    self.numTF.leftView = letfV;
    self.numTF.leftViewMode = UITextFieldViewModeAlways;
    self.numTF.borderStyle = UITextBorderStyleNone;
    self.numTF.layer.cornerRadius = AdaptedWidth(10);
    self.numTF.backgroundColor = UIColorHex(#F7F7F7);
    self.numTF.font = kDefaultFont(14);
    self.numTF.keyboardType = UIKeyboardTypeDecimalPad;
    self.numTF.returnKeyType = UIReturnKeyDone;
    [self.numTF addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
    self.valueLab = [UILabel new];
    self.valueLab.textColor = UIColorHex(999999);
    self.valueLab.font = kDefaultFont(11);
    [self.contentView addSubview:self.valueLab];
    [self.valueLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.numTF.mas_left).offset(3);
        make.right.mas_equalTo(-kNormalSpace);
        make.top.equalTo(self.numTF.mas_bottom);
    }];
    
    UILabel*accountTip = [UILabel new];
    accountTip.textColor = UIColorHex(333333);
    accountTip.font = kDefaultFont(15);
    [self.contentView addSubview:accountTip];
    [accountTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kNormalSpace);
        make.top.equalTo(self.numTF.mas_bottom).offset(AdaptedWidth(30));
    }];
    
    self.accountTF = [UITextField new];
    self.accountTF.returnKeyType = UIReturnKeyDone;
    [self.contentView addSubview:self.accountTF];
    [self.accountTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.top.equalTo(accountTip.mas_bottom).offset(5);
        make.height.mas_equalTo(AdaptedWidth(37));
    }];
    UIView*letfV1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 8, AdaptedWidth(30))];
    self.accountTF.leftView = letfV1;
    self.accountTF.leftViewMode = UITextFieldViewModeAlways;
    self.accountTF.borderStyle = UITextBorderStyleNone;
    self.accountTF.layer.cornerRadius = AdaptedWidth(10);
    self.accountTF.backgroundColor = UIColorHex(#F7F7F7);
    self.accountTF.font = kDefaultFont(14);
    self.accountTF.delegate =self;
    UILabel*bottomTip = [UILabel new];
    bottomTip.textColor = UIColorHex(999999);
    bottomTip.font = kDefaultFont(13);
    bottomTip.numberOfLines = 0;
    [self.contentView addSubview:bottomTip];
    [bottomTip mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.top.equalTo(self.accountTF.mas_bottom).offset(5);
    }];
    
    actionTip.text = XLocalized(@"买入数量");
    accountTip.text = XLocalized(@"接收账号");
    bottomTip.text = XLocalized(@"接收账号默认为自己,也可填写他人账户");
    self.numTF.placeholder = XLocalized(@"输入EOS数量");
    self.accountTF.placeholder = self.wallet.wallet_name;
    
    XThemeFlatButton *bottomBtn = [XThemeFlatButton button];
    [bottomBtn setTitle:XLocalized(@"购买") forState:UIControlStateNormal];
    [self.contentView addSubview:bottomBtn];
    [bottomBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bottomTip.mas_bottom).offset(AdaptedWidth(30));
        make.left.mas_equalTo(kNormalSpace);
        make.right.mas_equalTo(-kNormalSpace);
        make.height.mas_equalTo(AdaptedWidth(40));
        make.bottom.mas_equalTo(AdaptedWidth(-50));
    }];
    kWeakSelf(self);
    segementView.resultBlock = ^(NSInteger index) {
        if (index==0) {
            weakself.valueLab.text = @"";
            weakself.numTF.text = @"";
            actionTip.text = XLocalized(@"买入数量");
            weakself.numTF.placeholder = XLocalized(@"输入EOS数量");
            accountTip.hidden = NO;
            weakself.accountTF.hidden = NO;
            bottomTip.hidden = NO;
            useTip.text = [NSString stringWithFormat:@"%@：%@",XLocalized(@"余额"),weakself.eosService.accountResult.core_liquid_balance];
            weakself.isSell = NO;
            [bottomBtn setTitle:XLocalized(@"购买") forState:UIControlStateNormal];
        }else{
            weakself.valueLab.text = @"";
            weakself.numTF.text = @"";
            actionTip.text = XLocalized(@"卖出数量（KB）");
            weakself.numTF.placeholder = XLocalized(@"输入内存数量");
            accountTip.hidden = YES;
            weakself.accountTF.hidden = YES;
            bottomTip.hidden = YES;
            useTip.text = [NSString stringWithFormat:@"%@：%@ KB",XLocalized(@"余额"),weakself.eosService.accountResult.ram_remaining?:@""];
            weakself.isSell = YES;
            [bottomBtn setTitle:XLocalized(@"出售") forState:UIControlStateNormal];
        }
    };
    
    [bottomBtn addTapBlock:^(UIButton * _Nonnull btn) {
        if (!weakself.numTF.text.length) {
            [weakself.view makeToast:weakself.numTF.placeholder];
            return ;
        }
        if (!weakself.isSell) {
            if (SNCompare(weakself.numTF.text.length?weakself.numTF.text:@"0",[weakself.eosService.accountResult.core_liquid_balance getDigital])==NSOrderedDescending) {
                [weakself.view makeToast:XLocalized(@"输入数量超过可用余额！")];
                return;
            }else{
                DLog(@"数量OK");
            }
            if (weakself.accountTF.text.length) {
                if (![RegularExp validateEosAccountName:weakself.accountTF.text]) {
                    [weakself.view makeToast:XLocalized(@"无效的账号！")];
                    return;
                }
                weakself.eosService.toUser = weakself.accountTF.text;
            }else{
                weakself.eosService.toUser = weakself.wallet.wallet_name;
            }
            [WalletTool checkPrivateInputPasswordWith:weakself.wallet complete:^(BOOL result,NSString * _Nonnull privateKey) {
                if (result) {
                    weakself.eosService.account = kContractName_EOSIO;
                    weakself.eosService.available_keys = @[VALIDATE_STRING(weakself.wallet.wallet_public_key)];
                    weakself.eosService.privateKey = privateKey;
                    weakself.eosService.actor = weakself.wallet.wallet_name;
                    weakself.eosService.action = ContractAction_BUYRAM;
                    NSString* ram_quant = [NSString stringWithFormat:@"%@ %@",[NSString stringWithFormat:@"%.*lf",kSymbolLength_EOS,[weakself.numTF.text.length?weakself.numTF.text:@"0" doubleValue]],kSymbolName_EOS];
                    weakself.eosService.ram_quant = ram_quant;
                    [MBProgressHUD showLoadTitile:@"" ToView:weakself.view];
                    [weakself.eosService buyRamComplete:^(BOOL success, NSString * _Nonnull errorMsg) {
                        if (success) {
                            weakself.numTF.text = @"";
                            [weakself getaccountInfo];
                        }
                        [MBProgressHUD hideHUDForView:weakself.view];
                        [weakself.view makeToast:errorMsg];
                    }];
                }
            }];
        }else{
            if (SNCompare(weakself.numTF.text.length?weakself.numTF.text:@"0",[weakself.eosService.accountResult.ram_remaining getDigital])==NSOrderedDescending) {
                [weakself.view makeToast:XLocalized(@"输入数量超过可用余额！")];
                return;
            }else{
                DLog(@"数量OK");
            }
            [WalletTool checkPrivateInputPasswordWith:weakself.wallet complete:^(BOOL result,NSString * _Nonnull privateKey) {
                if (result) {
                    weakself.eosService.account = kContractName_EOSIO;
                    weakself.eosService.available_keys = @[VALIDATE_STRING(weakself.wallet.wallet_public_key)];
                    weakself.eosService.privateKey = privateKey;
                    weakself.eosService.actor = weakself.wallet.wallet_name;
                    weakself.eosService.action = ContractAction_SELLRAM;
                    weakself.eosService.sell_ram = @(SNMul(weakself.numTF.text, @1024).floatValue);
                    [MBProgressHUD showLoadTitile:@"" ToView:weakself.view];
                    [weakself.eosService sellRamComplete:^(BOOL success, NSString * _Nonnull errorMsg) {
                        if (success) {
                            weakself.numTF.text = @"";
                            [weakself getaccountInfo];
                        }
                        [MBProgressHUD hideHUDForView:weakself.view];
                        [weakself.view makeToast:errorMsg];
                    }];
                }
            
            }];
        }
        
    }];
}

- (void)textDidChange:(UITextField*)textField{
    self.valueLab.hidden = !textField.text.length;

    if (self.isSell) {
        if (self.eosService.ram_balance && textField.text.length) {
            NSString*tip = handlerDecimalNumber(SNMul(textField.text, self.eosService.ram_balance), NSRoundPlain, 4).stringValue;
            self.valueLab.text = [NSString stringWithFormat:@"≈ %@ %@",tip,kSymbolName_EOS];
        }
    }else{
        if (self.eosService.ram_balance && textField.text.length) {
            NSString*tip = handlerDecimalNumber(SNDiv(textField.text, self.eosService.ram_balance), NSRoundPlain, 2).stringValue;
            self.valueLab.text = [NSString stringWithFormat:@"≈ %@ KB",tip];
        }
    }
}
#pragma mark - Delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.numTF) {
        if (!self.isSell) {
            return [RegularExp controllTheAmountfNumberWithString:textField shouldChangeCharactersInRange:range replacementString:string maxDecimalLength:kSymbolLength_EOS];
        }else{
            return [RegularExp controllTheAmountfNumberWithString:textField shouldChangeCharactersInRange:range replacementString:string maxDecimalLength:4];
        }
    }
    return YES;
}
#pragma mark - getter
- (EOSService*)eosService{
    if (!_eosService) {
        _eosService = [EOSService new];
        _eosService.wallet = self.wallet;
    }
    return _eosService;
}

@end
